﻿using System;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using Microsoft.Xrm.Sdk;

namespace RibbonEditor.Forms.WebRessources
{
    public partial class CreateWebResourceDialog : Form
    {
        XmlNode currentNode;

        string filePath;

        public CreateWebResourceDialog(XmlNode node)
        {
            InitializeComponent();

            this.currentNode = node;
            this.FillControls();
            this.SetToolTips();
        }

        private void SetToolTips()
        {
        //    this.toolTip.SetToolTip(this.lblDisplayName, "Set the display name of the web resource");
        //    this.toolTip.SetToolTip(this.lblName, "Set the schema name of the web resource");
        //    this.toolTip.SetToolTip(this.lblFileName, "Set the path to the web resource in the customization archive");
        //    this.toolTip.SetToolTip(this.lblType, "Set the type of the web resource");
        }

        private void FillControls()
        {
            this.ecType.Values = Enum.GetNames(typeof(Enumerations.WebResourceType));

            if (this.currentNode != null && this.currentNode.Name == "WebResource")
            {
                this.strDisplayName.Value = this.currentNode.SelectSingleNode("DisplayName").InnerText;
                this.strName.Value = this.currentNode.SelectSingleNode("Name").InnerText;
                this.strFileName.Value = this.currentNode.SelectSingleNode("FileName").InnerText;

                this.ecType.SelectedValue = Enum.GetName(typeof(Enumerations.WebResourceType), int.Parse(this.currentNode.SelectSingleNode("WebResourceType").InnerText));

                this.lblHeader.Text = "Web resource properties";
                this.btnValidate.Text = "Close";
                this.btnCancel.Visible = false;

                this.strDisplayName.Enabled = false;
                this.strName.Enabled = false;
                this.strFileName.Enabled = false;
                this.ecType.Enabled = false;
                this.btnBrowseFile.Enabled = false;
                this.txtFile.Enabled = false;
            }
        }

        private void btnValidate_Click(object sender, EventArgs e)
        {
            if (this.btnValidate.Text == "OK" && (this.currentNode == null || this.currentNode.Name != "WebResource"))
            {
                try
                {
                    if (this.currentNode == null)
                    {
                        this.currentNode = MainForm.sManager.CustomizationFile.CreateElement("WebResources");

                        XmlNode refNode = MainForm.sManager.CustomizationFile.SelectSingleNode("ImportExportXml/optionsets");

                        if (refNode != null)
                        {
                            MainForm.sManager.CustomizationFile.DocumentElement.InsertAfter(this.currentNode, refNode);
                        }
                        else
                        {
                            MainForm.sManager.CustomizationFile.DocumentElement.AppendChild(this.currentNode);
                        }
                    }

                    #region Create web ressource

                    Entity webR = new Entity("webresource");
                    webR["displayname"] = this.strDisplayName.Value;
                    webR["webresourcetype"] = new OptionSetValue((int)(Enumerations.WebResourceType)Enum.Parse(typeof(Enumerations.WebResourceType), this.ecType.SelectedValue));
                    webR["name"] = this.strName.Value;
                    webR["content"] = this.getEncodedFileContents(this.txtFile.Text);

                    Guid wrId = MainForm.service.Create(webR);

                    // Ajout des éléments pour la suite du traitement
                    webR["webresourceid"] = wrId;
                    webR["filename"] = this.strFileName.Value;

                    #endregion

                    MainForm.sManager.AddComponent(61, wrId, webR["name"].ToString(), webR);

                    #region OLD Treatment
                    /*
                    AddSolutionComponentRequest request = new AddSolutionComponentRequest()
                    {
                        ComponentType = 61, // Web Resource
                        SolutionUniqueName = Form1.sManager.CurrentSolution["uniquename"].ToString(),
                        ComponentId = wrId
                    };

                    Form1.service.Execute(request);

                    #endregion

                    #region Xml Web ressources update

                    if (!this.ecType.IsValid())
                    {
                        throw new Exception("Please select a type for the web resource!");
                    }

                    XmlNode webResourceNode = XmlHelper.AddNode(this.currentNode, "WebResource");

                    XmlNode IdNode = XmlHelper.AddNode(webResourceNode, "WebResourceId");
                    IdNode.InnerText = wrId.ToString("B");

                    XmlNode nameNode = XmlHelper.AddNode(webResourceNode, "Name");
                    nameNode.InnerText = this.strName.Value;

                    XmlNode displayNameNode = XmlHelper.AddNode(webResourceNode, "DisplayName");
                    displayNameNode.InnerText = this.strDisplayName.Value;

                    XmlNode typeNode = XmlHelper.AddNode(webResourceNode, "WebResourceType");
                    Enumerations.WebResourceType type = (Enumerations.WebResourceType)Enum.Parse(typeof(Enumerations.WebResourceType), this.ecType.SelectedValue);
                    typeNode.InnerText = ((int)type).ToString();

                    XmlNode fileNameNode = XmlHelper.AddNode(webResourceNode, "FileName");
                    fileNameNode.InnerText = this.strFileName.Value;

                    //XmlNode isCustomizableNode = XmlHelper.AddNode(webResourceNode, "IsCustomizable");
                    //isCustomizableNode.InnerText = "1";

                    #endregion
                     * */
                    #endregion

                    FileInfo fi = new FileInfo(MainForm.sManager.CustomizationFilePath);
                    if (!Directory.Exists(fi.DirectoryName + "\\WebResources"))
                    {
                        Directory.CreateDirectory(fi.DirectoryName + "\\WebResources");
                    }

                    File.Copy(this.filePath, fi.DirectoryName + "\\WebResources\\" + this.strName.Value, true);

                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                catch (Exception error)
                {
                    MessageBox.Show(this, error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        //Encodes the Web Resource File
        public string getEncodedFileContents(String pathToFile)
        {
            FileStream fs = new FileStream(pathToFile, FileMode.Open, FileAccess.Read);
            byte[] binaryData = new byte[fs.Length];
            long bytesRead = fs.Read(binaryData, 0, (int)fs.Length);
            fs.Close();
            return System.Convert.ToBase64String(binaryData, 0, binaryData.Length);
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void btnBrowseFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "Select a file to become a web resource";
            ofd.Filter = "HTML file (*.html)|*.html|CSS Stylesheet file (*.css)|*.css|JScript file (*.js)|*.js|XML file (*.xml)|*.xml|PNG image (*.png)|*.png|JPG image (*.jpg)|*.jpg|GIF image (*.gif)|*.gif|XAP silverlight file (*.xap)|*.xap|XSL Stylesheet file (*.xsl)|*.xsl|ICO file (*.ico)|*.ico";
            
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                FileInfo fi = new FileInfo(ofd.FileName);

                this.txtFile.Text = fi.FullName;
                this.strFileName.Value = "/WebResource/" + fi.Name;
                this.strName.Value = fi.Name;
                this.filePath = fi.FullName;

                switch (fi.Extension.ToLower())
                {
                    case ".html":
                        this.ecType.SelectedValue = Enumerations.WebResourceType.Html.ToString();
                        break;
                    case ".css":
                        this.ecType.SelectedValue = Enumerations.WebResourceType.Css.ToString();
                        break;
                    case ".js":
                        this.ecType.SelectedValue = Enumerations.WebResourceType.JScript.ToString();
                        break;
                    case ".xml":
                        this.ecType.SelectedValue = Enumerations.WebResourceType.Xml.ToString();
                        break;
                    case ".png":
                        this.ecType.SelectedValue = Enumerations.WebResourceType.Png.ToString();
                        break;
                    case ".jpg":
                        this.ecType.SelectedValue = Enumerations.WebResourceType.Jpg.ToString();
                        break;
                    case ".gif":
                        this.ecType.SelectedValue = Enumerations.WebResourceType.Gif.ToString();
                        break;
                    case ".xap":
                        this.ecType.SelectedValue = Enumerations.WebResourceType.Silverlight.ToString();
                        break;
                    case ".xsl":
                        this.ecType.SelectedValue = Enumerations.WebResourceType.Stylesheet_XSL.ToString();
                        break;
                    case ".ico":
                        this.ecType.SelectedValue = Enumerations.WebResourceType.Ico.ToString();
                        break;
                }
            }
        }
    }
}
